package com.enfry.common.util.excel;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jxl.Workbook;


public class ExcelParser {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	protected List<SheetParser> sheetParsers = new ArrayList<SheetParser>();
	
	public void addSheetParser(SheetParser sheetParser) {
        sheetParsers.add(sheetParser);
    }
	
    public List<SheetParser> getSheetParsers() {
		return sheetParsers;
	}

	public void setSheetParsers(List<SheetParser> sheetParsers) {
		this.sheetParsers = sheetParsers;
	}

	public List[] parseExcel(Map context, String fileName) {
        InputStream is = null;
        try {
        	logger.info("=====================parseExcel");
        	is = new FileInputStream(fileName);
        	logger.info("====================="+is);
            return parseExcel(context, is);
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
        	if(is!=null){
        		try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        }
		return null;
    }
	
    /**
     * 重载ExcelParser中相应方法，利用POI来解析Excel文件
     * @param context
     * @param is
     * @return
     * @throws ExcelParseException
     */
    public List[] parseExcel(Map context, InputStream is)  throws Exception{
       Workbook wb = null;
       try {
				try {
					wb = Workbook.getWorkbook(is);
				} catch(Exception e){
					logger.info("=====================读取Excel出错");
					throw new Exception("读取Excel出错:"+e.getMessage(),e);
				}
				
		        //判断实际读入的sheet的数目是否少于期望的sheet的数目
		        int sheetSize = wb.getNumberOfSheets();
		        int parserSize = sheetParsers.size();
		        if (sheetSize < parserSize) {
		            throw new Exception("Excel文件的表单数(" + sheetSize + ")少于期望的数目(" + parserSize + ")");
		        }
		        
		        List[] result = new List[parserSize];
		        for (int i = 0; i < parserSize; i++) {
		        	// 模板中有多个sheet，有些sheet不需要进行解析，所以要根据sheet名称获取需要sheet进行解析  
		            SheetParser parser = sheetParsers.get(i);
		            result[i] = parser.parseSheet(context, wb.getSheet(i));
		        }
		        return result;
	       } catch (Exception e) {
	    	   throw new Exception("解析Excel出错:"+e.getMessage(),e);
	       }finally{
	    	   if(wb!=null){
	    		   wb.close();
	    	   }
	       }
    }
}
